import { useEffect, useRef } from 'react';
import { confirmDialog } from '../components/dialog';
import LoadingMask from '../components/loadingMask';
import main from '../main';
import { detailRemove } from '../redux/detailReducer';
import { createStoreListKey, listRequest } from '../redux/listReducer';
import { createStorePaginateListKey, paginateRequest } from '../redux/paginateReducer';
import store from '../redux/store';
import { defaultPageSize, defaultPageSizeOptions } from './defaultData';
import { Message } from '@arco-design/web-react';

interface Props {
  model: string;
  table: string;
  path?: string;
  type: 'list' | 'paginate';
}

interface RefreshProps {
  params?: any;
  forceRefresh?: boolean;
  callback?: (code?: number, msg?: string) => void;
}

interface PageUtils {
  /** 当前模块 */
  model: string;
  /** 当前表 */
  table: string;
  /** 当前页数 */
  pageNum: number;
  /** 当前第页的条数 */
  pageSize: number;
  /** 页面标签 */
  pageTag: string;
  /** 获取分页或列表数据的key */
  stateKey: string;
  /** 当前页面的默认参数 */
  params?: { [x: string]: any };
  /** 创建创建参数的方法 */
  createParams: () => { [x: string]: any };
  /** 刷新当前页面数据 */
  handleRefreshData: (arg?: RefreshProps) => void;
  /** 搜索按钮点击 */
  handleSearch: () => void;
  /** 重置按钮点击 */
  handleReset: (params?: { [x: string]: any }) => void;
  /** 删除按钮点击 */
  handleDelete: (ids: Array<string | number>) => void;
  /** 接收tab分页变化 */
  handlePageAndSizeChange: (pageNum: number, pageSize: number) => void;
  /** 随时接收最新的创建参数方法 */
  setFun: (createParams?: () => any) => void;
  /** 分页列表默认条数 */
  defaultPageSize: number;
  /** 分页列表可选条数 */
  defaultPageSizeOptions: Array<number>;
}

export default function usePageUtils({ model, table, path, type }: Props) {
  const pageTag = model + '/' + table + '/' + (path ?? 'list');
  let returnRef = useRef<PageUtils>({
    model,
    table,
    pageNum: main.currPageNum[pageTag] ?? 1,
    pageSize: main.currPageSize[pageTag] ?? defaultPageSize,
    pageTag: pageTag,
    stateKey: '',
    createParams,
    handleRefreshData,
    handleSearch,
    handleReset,
    handleDelete,
    handlePageAndSizeChange,
    setFun,
    params: main.currPageState[pageTag],
    defaultPageSize,
    defaultPageSizeOptions,
  });
  useEffect(() => {
    returnRef.current.stateKey = createKey();
  }, []); // eslint-disable-line

  function createParams() {
    return {};
  }

  function setFun(createParams?: () => any) {
    if (createParams) returnRef.current.createParams = createParams;
  }

  function createKey(_p?: any): string {
    if (type === 'list') {
      return createStoreListKey({
        model,
        table,
        path,
        params: _p ?? returnRef.current.createParams(),
      });
    } else {
      return createStorePaginateListKey({
        model,
        table,
        path,
        pageNum: returnRef.current.pageNum,
        pageSize: returnRef.current.pageSize,
        params: _p ?? returnRef.current.createParams(),
      });
    }
  }

  function handleRefreshData(args?: RefreshProps) {
    let { params, forceRefresh, callback } = args ?? {};
    let _params = params ?? returnRef.current.createParams();
    returnRef.current.stateKey = createKey(_params);
    returnRef.current.params = _params;
    main.currPageState[returnRef.current.pageTag] = _params;
    if (type === 'list') {
      store.dispatch(
        listRequest({
          model,
          table,
          path,
          params: _params,
          forceRefresh,
          callback,
        })
      );
    } else {
      store.dispatch(
        paginateRequest({
          model,
          table,
          path,
          pageNum: returnRef.current.pageNum,
          pageSize: returnRef.current.pageSize,
          params: _params,
          forceRefresh,
          callback,
        })
      );
    }
  }

  function handleSearch() {
    returnRef.current.pageNum = 1;
    _handlePageAndSizeChange(returnRef.current.pageNum, returnRef.current.pageSize);

    LoadingMask.show('正在搜索...');
    handleRefreshData({
      forceRefresh: true,
      callback: (code, msg) => {
        LoadingMask.hide();
        let _msg = code === 200 ? Message.success : Message.warning;
        _msg(msg ?? '');
      },
    });
  }

  function handleReset(params?: { [x: string]: any }) {
    returnRef.current.pageNum = 1;
    _handlePageAndSizeChange(returnRef.current.pageNum, returnRef.current.pageSize);
    handleRefreshData({ params });
  }

  async function handleDelete(ids: Array<string | number>) {
    if (!ids.length) {
      return Message.warning('请选择数据');
    }
    let tipsRes = await confirmDialog({ content: '确定要删除吗' });
    if (tipsRes !== 1) return;
    LoadingMask.show('正在删除...');
    store.dispatch(
      detailRemove({
        model,
        table,
        id: ids.join(','),
        callback(code, msg) {
          let _msg = code === 200 ? Message.success : Message.warning;
          handleRefreshData({ forceRefresh: true });
          LoadingMask.hide();
          _msg(msg ?? '');
        },
      })
    );
  }

  function handlePageAndSizeChange(pageNum: number, pageSize: number) {
    _handlePageAndSizeChange(pageNum, pageSize);
    handleRefreshData();
  }
  function _handlePageAndSizeChange(pageNum: number, pageSize: number) {
    returnRef.current.pageNum = pageNum;
    returnRef.current.pageSize = pageSize;
    main.currPageNum[returnRef.current.pageTag] = pageNum;
    main.currPageSize[returnRef.current.pageTag] = pageSize;
  }
  return returnRef.current;
}
